const Config = require('./Config.js')
const Utils=require('./utils.js');
// #ifndef APP-PLUS-NVUE
const store =require('../store');
// #endif
const MD5 = require('@/common/SDK/md5.min.js');
const CryptoJS = require('./crypto-js.js');

/* 接口请求封装 */
const httpReq={
	POST(options){
		options.method="POST";
		return httpReq.Request(options)
	},
	GET(options){
		options.method="GET";
		return httpReq.Request(options)
	},
	Request(options){
		/* 请求之前 */
		var defaultSetting={
			url: "",//请求HTTP地址
			data: {},//请求数据
			method: "POST", //请求方式 OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
			success:null, //成功回调方法
			header:{
				'Content-Type':"application/x-www-form-urlencoded"
			},
			// dataType:"json",
			fail:(res)=>{},//失败回调方法
			failFresh:(res)=>{},//刷新网络失败回调
			complete: (res)=>{},//完成回调方法
			showfailsure:(res)=>{},//弹框回调————确定
			showfailcancel:(res)=>{},//弹框回调————关闭
			failcb:(res)=>{},//接口code!=10000||code!=-1||code!=1回调
			loading:false,//是否显示加载中字样
			isLogin:false,//是否判断登录
			isFailShowModal:true,//code=0弹出错误提示框
			networktype:0,//1表示图片，2表示提示
			passurl:false
		}
		
		options=Object.assign(defaultSetting,options);
		let url=options.url;
		options.url=Config.ApiUrl+options.url;
		if(options.wholeurl){options.url=url;console.log(options.url)}
		// if(options.isLogin){
		// 	var hasLogin=store.default.state.hasLogin;//登录状态
		// 	if(!hasLogin){
		// 		uni.navigateTo({
		// 			url:"/pages/logins/login/login"
		// 		})
		// 		return;
		// 	}
		// }
		if(options.loading){
			uni.showLoading({
				mask:true
			})
		}
		// 参数加密
		options.data.request_time = parseInt(Date.now() / 1000);
		options.data.requester = "MYHAPP";
		options.data.interfaceServices = "MYH"
		options.data.order_no = getOrderNumber();
		if(Object.keys(options.data).length==0){
			console.log('options.data没有传任何参数')
		}
		var temp = options.data;
		options.data=getAesString(Utils.Signature(options.data))
		temp.sign = options.data;
		options.data = temp;
		// 设置头部token
		var utoken=Utils.TimeStorage.geted('utoken')
		var ctoken=Utils.TimeStorage.Get('ctoken')
		options.header.utoken=utoken//给头部设置utoken
		options.header.ctoken=ctoken//给头部设置ctoken
		
		/* END请求之前 */
		function ajax(resolve,reject){
			// request成功
			var apiSuccess=options.success;
			var apiFailsure=options.showfailsure;
			var apiFailcancel=options.showfailcancel;
			var failcb=options.failcb;
			// request失败
			var apiFail=options.fail;
			var failFresh=options.failFresh
			options.complete=res=>{//从响应头获取token，重新存储
				if(res.header){
					let utoken=res.header.utoken;
					if(utoken)Utils.TimeStorage.Set("utoken",utoken)
				}
			}
			options.success=res=>{
				// #ifndef APP-PLUS-NVUE
				store.default.state.isConnected=true;
				// #endif
				if(options.loading)uni.hideLoading()
				if(res.statusCode==200){
					var result=res.data;
					if(options.passurl&&result.code!=-1){
						apiSuccess(result)
						resolve(result)
					}else if(!options.passurl&&(result.code==10000||result.code==1)){ //不弹窗
						apiSuccess(result)
						resolve(result)
					}else if(result.code==-1){
						// #ifndef APP-PLUS-NVUE
						store.default.commit('logout');
						// #endif
						uni.showToast({
							title:"请先登录",
							icon:"none",
							complete:(res)=>{
								uni.navigateTo({
									url:"/pages/login/login"
								})
								return false;
							}
						})
					}else{
						uni.hideLoading()
						failcb(result)
						if(options.isFailShowModal){
							Utils.showModal({
								content: result.message,
								success:(res)=>{
									if(res.confirm){
										apiFailsure(result)
									}
								}
							})
						}
					}
				}else{
					// var msg=res.errMsg;
					//  if(res.statusCode==404){
					// 	 msg="接口未找到"
					//  }else{res.statusCode==500}{
					// 	 msg="接口未响应"
					//  }
					//  Utils.showModal({
					// 	title: msg,
					//  	content: res.errMsg
					//  })
				}
			}
			options.fail=res=>{
				// console.log('页面:'+Utils.Pages().route);
				console.log('接口:'+options.url)
				uni.hideLoading();
				let err=res.errMsg;
				// #ifndef APP-PLUS-NVUE
				if(!store.default.state.isConnected){//网络未链接
					if(options.networktype==1){
						if(options.that!=undefined){//是pageload页面
							options.that.listnull=true;
							// options.that.listData=[]
						}
					}
					if(options.networktype==2){
						uni.showToast({icon:"none",title:"请检查网络"})
					}
					failFresh()
				}
			
				// else if(err="request:fail timeout"){//请求超时
				// 	store.default.state.isConnected=false;
				// }
				else {
					// Utils.showModal({
					// 	content:err
					// })
				}
				// #endif
				reject(res)
			}
			uni.request(options)
		}
		const promiseObj = new Promise(ajax);
		return promiseObj;
	},
	upLoadFile(options){
		/* 请求之前 */
		var defaultSetting={
			url: "",//请求HTTP地址
			filePath:"",
			name:"",
			header:{},
			formData:{},
			success:null, //成功回调方法
			fail:(res)=>{},//失败回调方法
			complete: (res)=>{},//完成回调方法
		}
		
		options=Object.assign(defaultSetting,options);
		let url=options.url;
		options.url=Config.ApiUrl+options.url;
		if(options.wholeurl){options.url=url;console.log(options.url)}
		// 参数加密
		options.formData.request_time = parseInt(Date.now() / 1000);
		options.formData.requester = "MYHAPP";
		options.formData.interfaceServices = "MYH"
		options.formData.order_no = getOrderNumber();
		if(Object.keys(options.formData).length==0){
			console.log('options.formData没有传任何参数')
		}
		var temp = options.formData;
		options.formData=getAesString(Utils.Signature(options.formData))
		temp.sign = options.formData;
		options.formData = temp;
		// 设置头部token
		var utoken=Utils.TimeStorage.geted('utoken');
		options.header.utoken=utoken//给头部设置utoken
		
		/* END请求之前 */
		function ajax(resolve,reject){
			// request成功
			var apiSuccess=options.success;
			var apiComplete=options.complete
			var failcb=options.failcb;
			// request失败
			var apiFail=options.fail;
			var failFresh=options.failFresh
			
			options.success=res=>{
				if(options.loading)uni.hideLoading()
				if(res.statusCode==200){
					var result=res.data;
					if(typeof result == 'string'){
						result = JSON.parse(result)
					}
					if(result.code==10000){
						apiSuccess(result)
						resolve(result)
					}else if(result.code==-1){
						uni.showToast({
							title:"请先登录",
							icon:"none",
							complete:(res)=>{
								uni.navigateTo({
									url:"/pages/login/login"
								})
							}
						})
					}else{
						// failcb(result)
					}
				}else{
			
				}
			}
			options.complete=res=>{//从响应头获取token，重新存储
				if(res.header){
					let utoken=res.header.utoken;
					if(utoken)Utils.TimeStorage.Set("utoken",utoken)
				}
				let result = res.data
				if(typeof result == 'string'){
					result = JSON.parse(result)
				}
				apiComplete(result)
				
			}
			options.fail=res=>{
				// console.log('页面:'+Utils.Pages().route);
				console.log('接口:'+options.url)
				uni.hideLoading();
				let err=res.errMsg;
				// #ifndef APP-PLUS-NVUE
				if(!store.default.state.isConnected){//网络未链接
				}
				else {
				}
				// #endif
				reject(res)
			}
			uni.uploadFile(options)
		}
		const promiseObj = new Promise(ajax);
		return promiseObj;
	}
}


 function getAesString(data){//加密
	const sign_key=Config.sign_key;
	const sign_iv=Config.sign_iv;
    var key  = CryptoJS.enc.Utf8.parse(sign_key);
    var iv   = CryptoJS.enc.Utf8.parse(sign_iv);
    var encrypted =CryptoJS.AES.encrypt(data,key,
        {
            iv:iv,
            mode:CryptoJS.mode.CBC,
            padding:CryptoJS.pad.Pkcs7
        });
    return encrypted.toString();    //返回的是base64格式的密文
    
}
   //获取六位随机数字
    function randSixNum() {
        let randnum = ('111111' + Math.floor(Math.random() * 999999)).slice(-6);
        return randnum;
    }
    //订单号
    function getOrderNumber() {
		 return formatDate(Date.now(), "yyyyMMddhhmmss") + '' + randSixNum() + "" + Date.now();
    }
	function formatDate(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
        date = new Date(date)
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        let o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'h+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds()
        };
        // 遍历这个对象
        for (let k in o) {
            if (new RegExp(`(${k})`).test(fmt)) {
                let str = o[k] + '';
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
            }
        }
        return fmt;
    }
	function padLeftZero(str) {
        return ('00' + str).substr(str.length);
    }
/* 分页加载封装 */
const pageLoad=(options)=>{
			/**
			 * 默认设置
			 */
			var defaultSetting = {
				isReload: false,//是否重载，可用于初次加载或下拉刷新
				that: null,//当前页面对象（用于设置分页状态）
				isAutoMerge: true,//是否自动合并数据（分页合并之前数据），默认自动合并
				emptyList:true,
				url: '',//请求数据接口地址
				data: null,//请求参数
				success: null,//成功回调
				before:null,
			};
			var setting=Object.assign(defaultSetting,options)
			var _this = setting.that;
			var pageIndex=_this.page;
			var pageSize=_this.pageSize||10;
			var listLen=_this.listLen||10;
			// console.log(setting.isReload,pageIndex)
			
			//是否重载，可用于初次加载或下拉刷新
			let listData = _this.listData;
			setting.emptyList=setting.isReload&&setting.emptyList==undefined?true:setting.emptyList;
			if (setting.isReload) { 
				pageIndex = 1;_this.loadtype=0; _this.listnull=false;
				if(setting.emptyList){_this.listData=[];}
				_this.text2="—————— 已经到底了哦 ——————"
			}
			// console.log(_this.listData)
			/* 
			 loadtype
			 0:加载完成
			 1：加载中
			 2：数据加载完结
			 */
			if (_this.loadtype==2||_this.loadtype==1) { return; }
			var options_success = setting.success;
			setting.success = (res) => {
				if (typeof setting.before == 'function') {
						setting.before(res);
				}
				if (res) {
					_this.loadtype=1;
					if (setting.isAutoMerge) {
						//合并当前已有数据
						var data = _this.listData || [];
						if(setting.isReload){data=[]}
						var reslist=res.data;
						data = data.concat(reslist);
						//保存当前数据
						
						setTimeout(()=>{
							_this.listData=data;
							_this.$forceUpdate();
							// 设置状态
							_this.loadtype=0;
							++pageIndex
							setting.data.page = pageIndex;
							_this.page=pageIndex;
							if(_this.listData.length==0&&reslist.length==0){
								_this.listnull=true
							}
							if(_this.listData.length>0&&reslist.length<pageSize){
							   if(_this.listData.length<=_this.listLen){
								_this.text2=" "
							   }
							   _this.loadtype=2;
							}
						},80)
					}
				}
				else {
					// uni.showModal({
					// 	title: '',
					// 	confirmText:"确定",
					// 	showCancel:false,
					// 	content: res.errMsg
					// });
				}
				//回调原成功事件
				if (typeof options_success == 'function') {
					options_success(res);
				}
			}
			setting.data.page = pageIndex;
			_this.page=pageIndex;
			setting.data.pageSize = _this.pageSize?_this.pageSize:'10';
			//加载数据
			return httpReq.POST(setting)
	}


module.exports={
	httpReq,
	pageLoad,
}